﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using StockTrader.API.TradingAlgos;
using StockTrader.Broker.IciciDirect;
using StockTrader.Common;
using StockTrader.Core;
using StockTrader.Platform.Logging;
using StockTrader.Stocks.Utilities.Broker;
using StockTrader.Utilities;
using StockTrader.Utilities.Broker;

namespace StockTrader.UI.Trader
{
    public partial class Login : Form
    {
        private void StartGetQuoteThreads()
        {
            // Separate GetQuote threads in background
            //DateTime from = DateTime.Now.AddYears(-2);
            //DateTime to = DateTime.Now;
            //BrokerErrorCode errorCode = BrokerErrorCode.Success;

            string symbol = "NIFTY";
            InstrumentType instrument = InstrumentType.FutureIndex;
            DateTime expiryDate = MarketUtils.GetExpiryExactDate(new DateTime(2011, 4, 28));


            DerivativeSymbolQuoteToGet dqg = new DerivativeSymbolQuoteToGet(symbol, instrument, expiryDate, 0);

            StartGetQuoteThread(dqg); // Future Index thread

            instrument = InstrumentType.OptionCallIndex;
            // Index Call option threads
            for (int i = 5800; i <= 6000; i = i + 100)
            {
                dqg = new DerivativeSymbolQuoteToGet(symbol, instrument, expiryDate, i);
                StartGetQuoteThread(dqg);
            }

            instrument = InstrumentType.OptionPutIndex;
            // Index Call option threads
            for (int i = 5700; i >= 5500; i = i - 100)
            {
                dqg = new DerivativeSymbolQuoteToGet(symbol, instrument, expiryDate, i);
                StartGetQuoteThread(dqg);
            }
            //errorCode = BrokerUtils.GetDerivativeQuote(_iciciDirectAccount, dqg);
            //_iciciDirectAccount.GetDerivativeQuote("NIFTY", InstrumentType.FutureIndex, expiryDate, 0, out dqi);
            //_iciciDirectAccount.GetDerivativeQuote("NIFTY", InstrumentType.OptionCallIndex, expiryDate, 5800, out dqi);
            //_iciciDirectAccount.GetDerivativeQuote("NIFTY", InstrumentType.OptionPutIndex, expiryDate, 5800, out dqi);
        }

        private void StartGetQuoteThread(DerivativeSymbolQuoteToGet dqg)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(BrokerUtils.GetDerivativeQuoteContinuously));

            BrokingAccountObject iciciAccObj = new BrokingAccountObject(_iciciDirectAccount);
            BrokingAccountThread iciciQuoteThread = new BrokingAccountThread();
            iciciAccObj.CustomData = dqg;

            iciciQuoteThread.brokerAccountObj = iciciAccObj;
            iciciQuoteThread.thread = thread;

            _brokerThreads.Add(iciciQuoteThread);

            iciciQuoteThread.thread.Name = "GetQuote Thread of \"" + _loginId + "\"";
            iciciQuoteThread.thread.IsBackground = true;

            iciciQuoteThread.thread.Start(iciciAccObj);
        }

        private void StartBooksCheckerThread()
        {
            // Separate Order and Trade books checker thread in background
            Thread thread = new Thread(new ParameterizedThreadStart(BrokerUtils.PollDerivativeTradeAndOrderbookContinuously));

            BrokingAccountObject iciciAccObj = new BrokingAccountObject(_iciciDirectAccount);
            BrokingAccountThread iciciBooksThread = new BrokingAccountThread();

            iciciBooksThread.brokerAccountObj = iciciAccObj;
            iciciBooksThread.thread = thread;

            _brokerThreads.Add(iciciBooksThread);

            iciciBooksThread.thread.Name = "Derivative books Thread of \"" + _loginId + "\"";
            iciciBooksThread.thread.IsBackground = true;

            iciciBooksThread.thread.Start(iciciAccObj);
        }

        public void AddTickToChart(ChartTickPoint point)
        {
            DateTime x = point.X;
            double y = point.Y;
            object[] parameters = { x, y };


            if (this.InvokeRequired)
            {// this prevents the invoke loop
                this.Invoke(new Action<ChartTickPoint>(this.AddTickToChart), new object[] { point }); // invoke call for _THIS_ function to execute on the UI thread
                //_chart.Invoke(_chart.addDataDel, point);
                //this.loginDashboardChart.Series[0].Points.AddXY(x.ToOADate(), y);
            }
            else
            {
                //function logic to actually add the datapoint goes here
                //_chart.Invoke(_chart.addDataDel, parameters);
                this.loginDashboardChart.Series[0].Points.AddXY(x.ToOADate(), y);
                this.loginDashboardChart.Invalidate();
                //_chart.AddTick(point);
            }
        }

        private void loginSubmit_Click1(object sender, EventArgs e)
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Success;
            //errorCode = TryLoggingIn();

            if (errorCode == BrokerErrorCode.Success)
            {
                SetPanelsOnLogin();

                this.welcomeMsg.Text = "Welcome " + _loginId + " !";

                //_chart.Show();

                //_chart.BackgroundImage = new Bitmap(@"d:\StockData\watermellongs.bmp");

                //_chart.BringToFront();



                StartLoginCheckerThread();

                //StartBooksCheckerThread();

                //// Successful login, now do the dance
                //List<DerivativeTradeInformation> trades = null;
                //_iciciDirectAccount.GetDerivativesTradeBook(DateTime.Now.AddYears(-2), DateTime.Now, InstrumentType.OptionCallIndex,
                //    false, out trades);

                //List<DerivativeOrderInformation> orders = null;
                //_iciciDirectAccount.GetDerivativesOrderBook(DateTime.Now.AddYears(-2), DateTime.Now, InstrumentType.OptionCallIndex,
                //    out orders);

                //StartGetQuoteThreads();

                // MultipleLotPeakDetector testing
                //_chart.Show();

                //string tickFile = @"D:\StockData\NIFTY-5Oct2005-16May2007-100000ticks.txt";

                string tickFile = @"D:\StockData\NIFTY-5Oct2005-7Apr2006-10000ticks.txt";

                //StartAlgoThread(tickFile);

                //BrokerAccountObject iciciAccObj = new BrokerAccountObject(_iciciDirectAccount);
                //iciciAccObj.CustomData = _chart;
                //iciciAccObj.CustomData2 = tickFile;

                //BrokerUtils.RunExperimentsOnAlgo(iciciAccObj);
                new Thread(new ParameterizedThreadStart(worker)).Start(new Action<ChartTickPoint>(this.AddTickToChart));
            }
        }

        private void worker(object obj)
        {
            Random rand = new Random();
            while (true)
            {
                ChartTickPoint point = new ChartTickPoint(DateTime.Now, rand.Next(1000), false, ChartTickType.Price);

                AddTickToChart(point);

                Thread.Sleep(1000);
            }
            //var _delegate = (Action<myData>)obj;
            //for (int x = 0; x < 50; x++)
            //{
            //    _delegate(new myData { X = x, Y = 2 * x });
            //    Thread.Sleep(1000);
            //}
        }

        private void StartAlgoThread1(string tickFile)
        {
            Thread thread = null;// new Thread(new ParameterizedThreadStart(AlgoRunUtils.GetAlgo));

            BrokingAccountObject iciciAccObj = new BrokingAccountObject(_iciciDirectAccount);
            BrokingAccountThread iciciAlgoThread = new BrokingAccountThread();

            AlgoData algoData = new AlgoData(tickFile, null, _getChartDataDelegate);

            iciciAccObj.CustomData = algoData;
            iciciAccObj.CustomData2 = _chart;

            iciciAlgoThread.brokerAccountObj = iciciAccObj;
            iciciAlgoThread.thread = thread;

            _brokerThreads.Add(iciciAlgoThread);

            iciciAlgoThread.thread.Name = "Algo Thread of \"" + _loginId + "\"";
            iciciAlgoThread.thread.IsBackground = true;

            iciciAlgoThread.thread.Start(iciciAccObj);
        }
    }

}